package com.powernode.teatraceability.controller.image;


import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
@RequestMapping("/*/image")
public class ImageController {

    @GetMapping
    public void getImage(@RequestParam String path,
                         HttpServletResponse response){
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("images"+path);
        response.setContentType("image/jpeg");
        if(in != null){
            try {
                int totalBytes = in.available();
                byte[] bytes = new byte[totalBytes];
                in.read(bytes);
                in.close();
                ServletOutputStream outputStream = response.getOutputStream();
                outputStream.write(bytes);
                outputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @PostMapping("/{dirName}")
    public String setImage(MultipartFile file,
                           @PathVariable String dirName){
        InputStream in = null;
        OutputStream out = null;
        try {
            in = file.getInputStream();
            out = new FileOutputStream("src/main/resources/images/" + dirName);
            byte[] bytes = new byte[1024 * 100];// 100kb
            int cnt = 0;
            while ((cnt = in.read(bytes)) != -1) {
                out.write(bytes, 0, cnt);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            if (in!=null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "/"+dirName+"/" + file.getName();
    }


}
